package net.dntuan.jaxbdemo.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import net.dntuan.jaxbdemo.model.Channel;
import net.dntuan.jaxbdemo.model.Item;
import net.dntuan.jaxbdemo.model.RSS;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;

/**
 * IMPORTANT NOTE: Open the felix console at the configuration tab
 * (/system/console/configMgr) and search for "Apache Sling Servlet/Script
 * Resolver and Error Handler". Here you’ll have to add “/path/” to the "Execution
 * Paths" section.
 * 
 * @author tuandn
 * 
 */
@Component(immediate = true, metatype = true, description = "Demonstrate parsing xml string to Java Object using Jaxb")
@Service(Servlet.class)
@Properties({ 
	@Property(name = "sling.servlet.paths", value = "/apps/jaxb/parsing/xml/demo"), 
	@Property(name = "sling.servlet.methods", value = "GET") })
public class ParseXmlServlet extends SlingSafeMethodsServlet {
    private static final long serialVersionUID = -581602408282175163L;

	@Override
	protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(RSS.class);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			
			URL arsenalRss = new URL("http://www.teamtalk.com/arsenal/rss");
			RSS rss = (RSS) unmarshaller.unmarshal(arsenalRss.openStream());

			Channel channel = rss.getChannel();

			PrintWriter writer = response.getWriter();
			writer.println("Channel Title: " + channel.getTitle());
			writer.println("Published Date: " + channel.getLastBuildDate());

			List<Item> items = channel.getItem();
			int counter = 0;
			for (Item item : items) {
				writer.println("Item: " + (++counter));
				writer.println("\tTitle: " + item.getTitle());
				writer.println("\tDate: " + item.getPubDate());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
